package com.hubiao.pay.merchant.service;

import com.hubiao.pay.common.domain.BusinessException;
import com.hubiao.pay.common.domain.CommonErrorCode;
import com.hubiao.pay.common.enums.AuditStatusEnum;
import com.hubiao.pay.merchant.api.MerchantService;
import com.hubiao.pay.merchant.api.dto.MerchantDTO;
import com.hubiao.pay.merchant.convert.MerchantConvert;
import com.hubiao.pay.merchant.domain.Merchant;
import com.hubiao.pay.merchant.mapper.MerchantMapper;

import javax.annotation.Resource;

/**
 * Description
 *
 * @author hubiao
 * @since 2020-11-01 21:40
 */
@org.apache.dubbo.config.annotation.Service
public class MerchantServiceImpl implements MerchantService {

    @Resource
    private MerchantMapper merchantMapper;

    @Resource
    private MerchantConvert merchantConvert;

    /**
     * 根据商户id获取商户信息
     *
     * @param id
     * @return
     */
    @Override
    public MerchantDTO queryMerchantById(Long id) {
        //1.查询数据库
        Merchant merchant = merchantMapper.selectById( id );
        //2。封装对象
        MerchantDTO merchantDTO = merchantConvert.dbConvertDTO( merchant );
        return merchantDTO;
    }


    /**
     * 注册商户实现
     *
     * @param merchantDTO
     * @return
     */
    @Override
    public MerchantDTO createMerchant(MerchantDTO merchantDTO) {
        //1.封装数据
//        Merchant merchant = new Merchant();
//        merchant.setMobile( merchantDTO.getMobile() );
        //1.2  0-未申请,1-已申请待审核,2-审核通过,3-审核拒绝  将商户的状态设置为未申请资质申请
//        merchant.setAuditStatus( "0" );
        //1.3 其他属性添加...
//        merchant.setMerchantName( merchantDTO.getMerchantName() );
        Merchant merchant = merchantConvert.dtoConvertDb( merchantDTO );
        //2.调用Mqpper向数据库写入数据
        merchantMapper.insert( merchant );
        //3.将保存的商户的id回传给dto
        merchantDTO.setId( merchant.getId() );
        return merchantDTO;
    }


    /**
     * 商户资质申请
     *
     * @param merchantId  商户id
     * @param merchantDTO 资质申请信息DTO
     * @return 返回用户DTO
     */
    @Override
    public MerchantDTO applyQualifications(Long merchantId, MerchantDTO merchantDTO) throws BusinessException {
        //1.判断参数是否存在
        if (merchantId == null || merchantDTO == null) {
            throw new BusinessException( CommonErrorCode.E_300009 );
        }
        //2.根据商户id查询商户，判断商户是否存在
        Merchant merchant = merchantMapper.selectById( merchantId );
        if (merchant == null) {
            throw new BusinessException( CommonErrorCode.E_200002 );
        }
        //3.封装数据
        Merchant merchantDb = merchantConvert.dtoConvertDb( merchantDTO );
        merchantDb.setMobile( merchant.getMobile() );
        merchantDb.setId( merchantId );
        /*已申请待审核*/
        merchantDb.setAuditStatus( AuditStatusEnum.TO_AUDIT.getKey() );
        //4.保存数据库
        merchantMapper.updateById( merchantDb );
        return merchantConvert.dbConvertDTO( merchantDb );
    }
}
